package com.revenant.driver.ui.activity.kotlin

import android.app.Activity
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.view.View.inflate
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.luck.picture.lib.PictureSelector
import com.luck.picture.lib.config.PictureConfig
import com.luck.picture.lib.config.PictureMimeType
import com.luck.picture.lib.entity.LocalMedia
import com.lzy.okgo.OkGo
import com.lzy.okgo.callback.StringCallback
import com.lzy.okgo.model.Response
import com.nanchen.compresshelper.CompressHelper
import com.qmuiteam.qmui.widget.dialog.QMUIBottomSheet.BottomListSheetBuilder
import com.revenant.driver.R
import com.revenant.driver.adapter.AddNewDriverInfoAdaper
import com.revenant.driver.bean.NewDriverAddInfo
import com.revenant.driver.bean.ShipperBean.FileUploadBean
import com.revenant.driver.databinding.ActivityNesDriverCompleteInformationBinding
import com.revenant.driver.utils.Constants
import com.revenant.driver.utils.GlideEngine
import com.revenant.driver.utils.GsonUtil
import kotlinx.android.synthetic.main.activity_nes_driver_complete_information.view.*
import java.io.File
import java.util.*

class NesDriverCompleteInformationActivity : AppCompatActivity() {
    val listName = listOf(
            "身份证正面照",
            "身份证反面照",
            "驾驶证正面照",
            "驾驶证反面照",
            "从业资格证")
    val listImage = listOf(
            R.mipmap.idforeground,
            R.mipmap.idback,
            R.mipmap.jaishizhengzhengmian,
            R.mipmap.jiashizhengfuye,
            R.mipmap.congyezigezhneg
    )
    val listUser: MutableList<NewDriverAddInfo> = mutableListOf()
    var adpter = AddNewDriverInfoAdaper()
    lateinit var recyclerView: RecyclerView
    var listimages = listOf<String>()
    var selectindex = -1
    private var selectList: List<LocalMedia> = ArrayList()
    private var context: Context? = null
    private lateinit var binding: ActivityNesDriverCompleteInformationBinding
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        context = this
//        binding = NewSecondImproveDriverInformationActivity_ViewBinding.setContentView(this, R.layout.activity_nes_driver_complete_information)

        binding = ActivityNesDriverCompleteInformationBinding.inflate(layoutInflater)
        val view = binding.root
        setContentView(view)
        /*遍历第一次*/
        recyclerView = findViewById(R.id.new_recyclerview)
        recyclerView.layoutManager = GridLayoutManager(this, 2)
        listName.mapIndexed { index, value ->
            value?.let {
                var user = NewDriverAddInfo()
                user.image = listImage[index]
                user.title = listName[index]
                listUser.add(user)
            }
        }

        recyclerView.adapter = adpter
        adpter.addData(listUser)

        adpter.setOnItemClickListener { adapter, view, position ->
            openTypeCarme(this)
            selectindex = position
        }

        binding.newIncludeBtn.new_include_btn.setOnClickListener {
            if (binding.newEdit.text?.trim()?.isEmpty()!!) {
                toast("请输入从业资格证号")
            } else {
                val data = adpter.data
                data.mapIndexed { index, newDriverAddInfo ->
                    if (newDriverAddInfo.imageUrl.isNullOrEmpty()) {
                        toast("请输入" + listName[index])
                    }
                }
            }
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode == Activity.RESULT_OK) {
            when (requestCode) {
                PictureConfig.CHOOSE_REQUEST -> {
                    selectList = PictureSelector.obtainMultipleResult(data)
                    for (media in selectList) {
                        if (!selectList.isEmpty()) {
                            val url = if (media.path.startsWith("content://")) media.androidQToPath else media.path
                            uploadAvatar(url, selectindex)
                        }
                    }
                }

            }
        }
    }

    fun openTypeCarme(activity: Activity) {
        val builder = BottomListSheetBuilder(activity)
        builder.setAddCancelBtn(true)
                .setGravityCenter(true)
                .setOnSheetItemClickListener { dialog, itemView, position, tag ->
                    dialog.dismiss()
                    if (position == 0) {
                        PictureSelector.create(activity)
                                .openCamera(PictureMimeType.ofImage())
                                .maxSelectNum(1)
                                .openClickSound(true)
                                .loadImageEngine(GlideEngine.createGlideEngine()) // 请参考Demo GlideEngine.java
                                .forResult(PictureConfig.CHOOSE_REQUEST)
                    } else if (position == 1) {
                        PictureSelector.create(activity)
                                .openGallery(PictureMimeType.ofImage())
                                .maxSelectNum(1)
                                .isCamera(false)
                                .openClickSound(true)
                                .loadImageEngine(GlideEngine.createGlideEngine()) // 请参考Demo GlideEngine.java
                                .forResult(PictureConfig.CHOOSE_REQUEST)
                    }
                }
        builder.addItem("拍照")
        builder.addItem("从相册选择")
        builder.build().show()
    }

    private fun uploadAvatar(path: String, select: Int) {
        val file = File(path)
        val newfile = CompressHelper.getDefault(this).compressToFile(file)
        OkGo.post<String>(Constants.UploadFile)
                .tag(this)
                .isMultipart(true)
                .params("file", newfile)
                .execute(object : StringCallback() {
                    override fun onSuccess(response: Response<String>) {
                        if (response.code() == 200) {
                            val fileUploadBean = GsonUtil.parseJsonWithGson(response.body(), FileUploadBean::class.java)
                            if (fileUploadBean.code == "0") {
                                adpter.data.get(select).imageUrl = fileUploadBean.data.url
                                adpter.data.get(select).selecttype = 0
//                                adpter.notifyItemChanged(select)
                            } else {
                                toast(response.message())
                            }
                        } else {
                            toast(response.message())
                        }
                    }

                    override fun onError(response: Response<String>) {
                        super.onError(response)
                    }
                })
    }


    fun Context.toast(message: CharSequence) =
            Toast.makeText(this, message, Toast.LENGTH_SHORT).show()
}

